﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Web.UI.HtmlControls;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web;

namespace ICeFramework.Web.Common
{
    public class HeadScriptManager
    {
        #region public static bool RegisterHeaderResource(Page currentPage, Type controlType, string url, ResourceType resourceType)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="currentPage"></param>
        /// <param name="controlType"></param>
        /// <param name="url"></param>
        /// <param name="resourceType"></param>
        /// <returns></returns>
        public static bool RegisterHeaderResource(Page page, Type controlType, string url, ResourceType resourceType)
        {
            Debug.Assert(HtmlUtil.EnsureWebResourceValid(url, controlType.Assembly, true));
            HtmlHead header = GetPageHeader();
            if (header == null)
            {
                throw new NotSupportedException("This page is missing a HtmlHead control which is required for the CSS stylesheet link that is being added. Please add <head runat=\"server\" />.");
            }

            string realUrl = url.StartsWith("/") || url.StartsWith("http://") ?
                url : page.ResolveUrl(page.ClientScript.GetWebResourceUrl(controlType, url));

            if (!IsHeaderResourceRegistered(controlType, realUrl))
            {
                switch (resourceType)
                {
                    case ResourceType.Javascript:
                        Literal literal = new Literal();
                        literal.Text = string.Format("<script src=\"{0}\" type=\"text/javascript\"></script>", realUrl);
                        header.Controls.Add(literal);

                        break;
                    case ResourceType.Stylesheet:
                        HtmlLink link = new HtmlLink();
                        link.Href = realUrl;
                        link.Attributes.Add("type", "text/css");
                        link.Attributes.Add("rel", "stylesheet");
                        header.Controls.Add(link);

                        break;
                    default:
                        return false;
                }
                return true;
            }
            return false;
        }
        #endregion

        public static bool IsHeaderResourceRegistered(Type controlType, string resourceUrl)
        {
            HtmlHead header = GetPageHeader();
            if (header == null)
            {
                return false; ///TODO: throw exception
            }

            string realUrl = resourceUrl.StartsWith("/") || resourceUrl.StartsWith("http://") ?
                 resourceUrl : header.Page.ResolveUrl(header.Page.ClientScript.GetWebResourceUrl(controlType, resourceUrl));

            foreach (Control c in header.Controls)
            {
                HtmlGenericControl htmlControl = c as HtmlGenericControl;
                if (htmlControl == null)
                {
                    continue;
                }

                bool isCss = htmlControl.TagName.ToLower() == "link" &&
                    htmlControl.Attributes["rel"].ToLower() == "stylesheet";

                bool isJs = htmlControl.TagName.ToLower() == "script" &&
                    htmlControl.Attributes["type"].ToLower() == "text/javascript";

                string src = htmlControl.Attributes["src"];

                if ((isCss || isJs) && src == realUrl)
                {
                    return true;
                }
            }


            return false;
        }

        private static HtmlHead GetPageHeader()
        {
            Page currentPage = HttpContext.Current.Handler as Page;
            if (currentPage == null)
            {
                return null;///TODO: throw exception
            }

            HtmlHead header = currentPage.Header;
            if (header == null)
            {
                header = HtmlUtil.FindControl<HtmlHead>(currentPage.Master.Controls);
            }

            return header;
        }
    }
}
